import { resolve } from 'path';
import { defineConfig, loadEnv } from 'vite';
import pages from 'vite-plugin-pages';
import fs from 'fs-extra';
import matter from 'gray-matter';
import { resolvePath, setupVitePlugins } from './build';

export default defineConfig(configEnv => {
  const viteEnv = loadEnv(configEnv.mode, process.cwd());
  const vitePath = resolvePath('./', import.meta.url);

  return {
    base: viteEnv.VITE_BASE_URL,
    plugins: [
      ...setupVitePlugins(configEnv, vitePath.src),
      pages({
        extensions: ['vue', 'ts', 'js', 'md'],
        dirs: 'src/pages',
        extendRoute(route) {
          const path = resolve(__dirname, route.component.slice(1));

          if (!path.includes('projects.md') && path.includes('.md')) {
            const md = fs.readFileSync(path, 'utf-8');
            const { data } = matter(md);
            // eslint-disable-next-line no-param-reassign
            route.meta = Object.assign(route.meta || {}, { frontmatter: data });
          }

          return route;
        }
      })
    ],
    server: {
      host: '0.0.0.0',
      port: 3200,
      open: true
    },
    build: {
      brotliSize: false
    }
  };
});
